import React, {Component} from 'react'
import {
    getAreaName,
    listManufacturer,
    listManufacturerOnID,
    queryManufacturerInfoAmount,
    queryManufacturerInfoAmountOnID,
    searchManufacturer
} from "../../../requests/Manufacturer"
import {Button, message, Spin, Table} from "antd"
import ManufacturerInfoType from '../../../types/ManufacturerInfo'
import ManufacturerInfo from '../../../types/ManufacturerInfo'
import {RootState} from '../../../reducers/index'
import {connect, ConnectedProps} from 'react-redux'
import ButtonGroup from 'antd/lib/button/button-group'
import DeleteManufacturerModal from "./Modals/DeleteManufacturerModal";
import {RouteComponentProps, withRouter} from 'react-router-dom'
import {devRes, getRes, prodRes} from "../../../configFile";
import UserType from '../../../types/UserType'
import Axios from 'axios'
import Search from 'antd/lib/input/Search'


interface PropsFromRedux extends ConnectedProps<typeof connector>, RouteComponentProps { }
interface IState {
    ManufacturerSource: Array<ManufacturerInfoType & { key: number }>       //显示信息
    amount: number                                                          //总共条目
    offset: number                                                          //偏移量
    limit: number                                                           //条数
    isLoading: boolean                                                       //是否加载中
    modifyModalVisible: boolean,                                             //编辑的模态框是否为显示状态
    isSearch: boolean
}

class ModifyManufacturerList extends Component<PropsFromRedux, IState> {

    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            isSearch: false,
            ManufacturerSource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isLoading: true,
            modifyModalVisible: false
        }
    }


    //获取厂商数据
    getManufacturer = async () => {
        try {
            this.setState({
                ...this.state,
                isLoading: true
            })
            const amountRes = this.props.userType === UserType.SUPERVISOR
                ?
                getRes(await queryManufacturerInfoAmount())
                :
                getRes(await queryManufacturerInfoAmountOnID(this.props.userID))

            if (amountRes.isSuccessful === false) {
                message.error(amountRes.message)
                return;
            }
            const res = this.props.userType === UserType.SUPERVISOR
                ?
                getRes(await listManufacturer(this.state.offset, this.state.limit))
                :
                getRes(await listManufacturerOnID(this.state.offset, this.state.limit, this.props.userID))
            if (res.isSuccessful === false) {
                message.error(res.message)
                return;
            }

            const areasRes: Array<devRes | prodRes> = (await Axios.all(res.data.map((itemManu: ManufacturerInfo) =>
                itemManu.manufacturerAddress.split(',')[0]).map((itemCode: string) => {
                    return getAreaName(itemCode)
                }))).map(item => getRes(item as devRes | prodRes).data)

            this.setState({
                ManufacturerSource: res.data.map((item: ManufacturerInfoType, index: number) =>
                    Object.assign({}, item, {
                        manufacturerAddress: areasRes[index] + ' ' + (item.manufacturerAddress.split(',').slice(1).join(''))
                    }, { key: item.manufacturerID })),
                amount: amountRes.data
            })
        }
        catch (error) {
            message.error(error.toString())
        }
        finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    componentDidMount() {
        this.getManufacturer()
    }

    columns = [{
        title: '厂商名称',
        dataIndex: 'manufacturerName',
        key: 'manufacturerName',
    },
    {
        title: '厂商地址',
        key: 'manufacturerAddress',
        dataIndex: 'manufacturerAddress',
    },
    {
        title: '联系方式',
        dataIndex: 'manufacturerTelephone',
        key: 'manufacturerTelephone',
    },
    {
        title: '操作',
        key: 'action',
        render: (record: ManufacturerInfoType) => (
            <ButtonGroup>
                <Button size='middle' type='primary' onClick={() => {
                    this.props.history.push(`modifyManufacturer/${record.manufacturerID}`)
                }}>编辑</Button>
                <Button size='middle' danger onClick={() => {
                    DeleteManufacturerModal(record.manufacturerID, record.manufacturerName, this.getManufacturer)
                }}>
                    删除
                </Button>
            </ButtonGroup>
        )
    }]

    onSearch: (values: string) => void = async values => {
        console.log(values)
        if (values === '') {
            await this.getManufacturer()
        } else {
            try {
                const res = getRes(await searchManufacturer(values))            //TODO:个人页面应该searchOnID
                if (res.isSuccessful) {
                    this.setState({ ManufacturerSource: res.data, amount: res.data.length, isSearch: true })
                } else {
                    console.error(res);
                    message.error("查询失败")
                }
            } catch (err) {
                message.error(JSON.stringify(err))
            }
        }
    }

    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Search placeholder="搜索" onSearch={values => this.onSearch(values)} allowClear={true} enterButton />
                    <Table columns={this.columns}
                        dataSource={this.state.ManufacturerSource}
                        pagination={{
                            onChange: (page, pageSize) => {
                                console.log(page, pageSize);
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    },()=>{
                                        this.getManufacturer()
                                    })
                                } else {
                                    console.error('pageSize == undefined')
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }} />
                </Spin>

            </div>
        )
    }
}

//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID,
        userType: state.loginReducers.userType
    }
}

const connector = connect(mapStateToProps)
export default withRouter(connector(ModifyManufacturerList))